|
|
|
|
|
|
|
run.The program runs the commands between the current Case statement and the next Case statement or the End Select statement. If the testvalue is not equal to the value expression, the program proceeds to compare the expression against the next Case statement. |
|
|
|
|
|
|
|
|
The End Select statement identifies the end of the Select Case block. |
|
|
|
|
|
|
|
|
|
Only one case in the Select Case block is executed for a given value of testvalue, even if more than one of the Case statements matches the value of the test expression.  |
|
|
|
|
|
|
CAUTION
|
|
|
|
|
The testvalue and value expressions should represent the same data type. For example, if the testvalue is a number, the values tested in the Case statements also must be numbers. |
|
|
|
|
|
|
|
|
|
|
Case statements within a Select Case structure can also handle lists, ranges, and comparisons of values in addition to discrete values. Note the use of Case Is < 0, Case 1 to 9, and Case Is > 50 in this example: |
|
|
|
|
|
|
|
|
nQtyOrdered = Val(txtQuantity)
Select Case nQtyOrdered
Case Is < 0 'note use of comparison
MsgBox "Order quantity cannot be negative!", vbExclamation
Exit Sub
Case 1, 2, 3 'note use of list
fDiscount = 0
Case 4 To 9 'note use of range
fDiscount = 0.03
Case 10 To 49
fDiscount = 0.08
Case Is > 50
fDiscount = 0.1
End Select |
|
|
|
|
|
|
|
|
The preceding examples work fine if your test variable matches one of the conditions in a Case statement. But how do you handle other values that are outside the ones for which you tested? You can have your code do something for all other possible values of the test expression by adding a Case Else statement to your program. The Case Else statement follows the last command of the last Case statement in the block. You then place the commands that you want executed between the Case Else and the End Select statements. |
|
|
|
|
|
|
|
|
You can use the Case Else statement to perform calculations for values not specifically called out in the Case statements. Alternatively, you can use the Case Else statement to let users know that they entered an invalid value. |
|
|
|
|
|
|
|
|
Consider a simple form used to enter three test scores for a student into three text boxes. A Calculate button computes the average of the test scores and uses a Select Case block to determine the student's letter grade based on the average test score. Listing 10.1 shows the code behind the Calculate button's Click event. |
|
|
|
|
|